package com.example.bishop.musicplayer_1;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private Button mBtnBottom;
    ImageView playIv,iconTv;
    TextView singerTv,songTv;
    RecyclerView musicRv;

    //数据源
    List<LocalMusicBean>mDatas;
    private MusicAdapter adapter;
    private int position;
    //记录当前正在播放的音乐的位置
    int currentPlayPosition = -1;
    //记录暂停音乐时进度条的位置
    int currentPausePositionInSong = 0;
    MediaPlayer mediaPlayer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBtnBottom = findViewById(R.id.btn_bottom);
        mBtnBottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,Button_Bottom.class);
                startActivity(intent);
            }
        });
        inteView();
        mediaPlayer = new MediaPlayer();
        mDatas = new ArrayList<>();
        //创建适配器对象
        adapter = new MusicAdapter(this, mDatas);
        musicRv.setAdapter(adapter);
        //设置布局管理器
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        musicRv.setLayoutManager(layoutManager);

        //加载本地数据源
        loadLocalMusicData();
        //设置每一项的点击事件
        setEventListener();
    }

    private void setEventListener() {//设置每一项的点击事件
        adapter.setOnItemClickListener(new MusicAdapter.OnItemClickListener() {
            @Override
            public void OnItemClick(View view, int position) {
                currentPlayPosition = position;
                LocalMusicBean musicBean = mDatas.get(position);
                //设置底部显示的歌手名和歌曲名
                singerTv.setText(musicBean.getSinger());
                songTv.setText(musicBean.getSong());
                stopMusic();
                //重置多媒体播放器
                mediaPlayer.reset();
                //设置新的播放路径
                try {
                    mediaPlayer.setDataSource(musicBean.getPath());
                    playMusic();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    /*点击播放按钮播放音乐，或点击暂停按钮继续播放音乐
    * 有两个情况：
    * 1.从暂停到播放
    * 2.从停止到播放
    * */
    private void playMusic() {//播放音乐的函数
        if (mediaPlayer!=null&&!mediaPlayer.
                isPlaying()) {
            if (currentPausePositionInSong == 0) {//从头开始播放
                try {
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }else{//从暂停处继续播放
                mediaPlayer.seekTo(currentPausePositionInSong);
                mediaPlayer.start();
            }
            playIv.setBackgroundResource(0);
            playIv.setImageResource(R.drawable.play1);
        }
    }

    private void stopMusic() {//停止音乐
        if (mediaPlayer !=null) {
            currentPausePositionInSong = 0;
            mediaPlayer.pause();
            mediaPlayer.seekTo(0);
            mediaPlayer.stop();
            playIv.setImageResource(R.drawable.pause1);
        }
    }

    private void pauseMusic() {//暂停音乐
        if (mediaPlayer!=null&&mediaPlayer.isPlaying()) {
            currentPausePositionInSong = mediaPlayer.getCurrentPosition();
            mediaPlayer.pause();
            playIv.setImageResource(R.drawable.pause1);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopMusic();
    }

    private void loadLocalMusicData() {
        //加载本地存储当中的mp3文件到集合当中
        //获取contentResolver对象
        ContentResolver resolver = getContentResolver();
        //获取本地音乐存储uri地址
        Uri uri = MediaStore.Audio.Media.INTERNAL_CONTENT_URI;
        //查询地址
        Cursor cursor = resolver.query(uri, null, null, null);
        //遍历cursor
        int id = 0;//给每首歌加id
        while (cursor.moveToNext()) {
            String song = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
            String singer = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
            String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
            id++;
            String sid = String.valueOf(id);
            String path = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
            long duration = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
            SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
            String time = sdf.format(duration);
            //将一行当中的数据封装到对象中
            LocalMusicBean bean = new LocalMusicBean(sid, song, singer, album, time, path);
            mDatas.add(bean);
        }
        //数据源变化，提示适配器更新
        adapter.notifyDataSetChanged();

    }

    private void inteView() {
        //初始化控件的函数
        iconTv = findViewById(R.id.music_BottomIcon);
        playIv = findViewById(R.id.iv_bottom_start);
        singerTv = findViewById(R.id.music_singer);
        songTv = findViewById(R.id.music_name);
        musicRv = findViewById(R.id.music_rv);
        playIv.setOnClickListener(this);
        songTv.setSelected(true);
        singerTv.setSelected(true);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_bottom_start:
                if (currentPlayPosition == -1) {
                    //没有选中要播放的音乐
                    Toast.makeText(this,"请选择音乐",Toast.LENGTH_SHORT).show();
                    return;
                }
                if (mediaPlayer.isPlaying()) {
                    //播放状态下需要暂停
                    pauseMusic();
                }else{
                    //没有播放音乐需要播放
                    playMusic();
                }
            break;
        }
    }


}